package com.meet.framework.utils;

import android.text.TextUtils;
import android.util.Log;

import com.meet.framework.BuildConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 封装logUtils工具类
 * Log不光作为日志的打印，还可以记录日志  -->File
 */
public class LogUtils {

    //LogUtils.i("");
    private static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");


    public  static void i(String text){
        if(BuildConfig.LOG_DEBUG) {
            if (!TextUtils.isEmpty(text)) {
                Log.i(BuildConfig.LOG_TAG,text);
//                writeToFile(text);
            }
        }
    }


    public  static void e(String text){
        if(BuildConfig.LOG_DEBUG) {
            if (!TextUtils.isEmpty(text)) {
                Log.e(BuildConfig.LOG_TAG,text);
//                writeToFile(text);
            }
        }
    }

    public  static  void writeToFile(String text){
        //文件路径
        String fileName="/sdcard/Meet/Meet.log";
        //时间 等级 内容
        String log=simpleDateFormat.format(new Date())+" "+text+"\n";
        //开始写入
        File fileGroup=new File(fileName);
        if(!fileGroup.exists()){
            fileGroup.mkdirs();
        }
        FileOutputStream fileOutputStream= null;
        BufferedWriter bufferedWriter=null;
        try {
            fileOutputStream = new FileOutputStream(fileName,true);
            //编码问题 GBK 正确 存入中文
            bufferedWriter=new BufferedWriter(
                    new OutputStreamWriter(fileOutputStream, Charset.forName("gbk")));
            bufferedWriter.write(log);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(bufferedWriter!=null){
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
